<?php
/**
 * | @author 大鹏^life <907215837@qq.com>
 * +----------------------------------------------------------------------
 * | @copyright 2016 - 2019 HQ
 * +----------------------------------------------------------------------
 * | @version $Id: 2019/4/25 16:23 jiahe_new Member.php 大鹏^life $
 * +----------------------------------------------------------------------
 */

namespace app\common\common\model\oldModel\order;

use app\api\server\storeServer;
use app\common\common\lib\CxjSdk;
use app\common\common\model\member\member;
use app\common\common\model\oldModel\coupons\Coupons;
use app\common\common\model\oldModel\member\memberCard;
use app\common\common\model\oldModel\member\memberCardLog;
use app\common\common\model\oldModel\OldBase;
use app\common\common\model\oldModel\member\member as old_member;
use app\common\common\Server\commonServer;
use app\common\common\Server\TemplateMessageServer;
use think\Log;

class  order extends OldBase  {
    protected $table = 'order_order';
    //错误消息
    public $error = '';
    //状态值
    public $status = true;
    //其他附带信息
    public $data = [];


    /**
     * 插入数据
     * @param $data
     * @return false|int
     */
    public function insertMember($data){
        return self::insertGetId($data);
    }

    /**
     * 不带分页的多条查询
     * @param $where
     * @return false|\PDOStatement|string|\think\Collection
     * @param $field 所查询字段
     * @param $order 排序
     */
    public function allByWhere($where,$field = array(),$order = 'order_id desc'){
        return $this->where($where)->field($field)->order($order)->selectToArray();
    }

    /**
     * 订单关联店铺
     * @param $where
     * @return false|\PDOStatement|string|\think\Collection
     */
    public function allOrderStore($where)
    {
        $list = $this->alias('od')->field('od.*,st.sname')
            ->join('store st', 'st.store_id = od.store_id')
            ->where($where)
            ->selectToArray();
        return $list;
    }
    /**
     * 带分页的查询
     * @param $where
     * @param $offset 第几页
     * @param $length 一页多少行
     * @param string $order
     * @return false|\PDOStatement|string|\think\Collection
     */
    public function selectByWhere($where, $limit = '0,100', $order='order_id desc'){
        $list = $this->where($where)->limit($limit)->order($order)->selectToArray();
        $count = $this->where($where)->count();
        $list['data'] = $list;
        $list['count'] = $count;
        return $list;
    }

    /**
     * 查询单条数据
     * @param $where
     * @return array|false|\PDOStatement|string|\think\Model
     */
    public function findByWhere($where,$field='*'){
        return $this->where($where)->field($field)->findToArray();
    }
    /**
     * 关联商家和订单
     * @param $storeId
     * @return false|\PDOStatement|string|\think\Collection
     */
    public function findStoreOrder($where)
    {


        $list = self::alias('od')->field('od.*,st.sname,sg.price,sg.current_price,sg.sort,sg.stock,sg.goods_pic_name spic_name,sg.dkid,sg.goods_pic spic,sg.is_meal,sg.is_takeout,sg.goods_type_id,sg.second_half')
            ->join('store st', 'st.store_id = od.store_id')
            ->where($where)
            ->findToArray();
        //todo aw:下面的可以单独令出去一个方法
        return $list;
    }

    /**
     * 通过open_id,修改用户信息
     * @param $open_id
     * @param $data
     * @return false|int
     */
    public function updateByOpenId($where, $data){

        return $this->save($data, $where);
    }

    /**
     * 首页需要的数据
     * @param $storeId
     * @return false|\PDOStatement|string|\think\Collection
     */
    public function allJoinWhere($storeId='')
    {

        $list = self::alias('o')->join('order_detail od', 'o.id=od.order_id')
            ->select()->toArray();
        //todo aw:下面的可以单独令出去一个方法
        return $list;
    }


    /**
     * 订单支付
     * @param string $order_code 订单编号
     * @param int $pay_type   支付方式  嘉和卡 5|早餐月卡 25|共享早餐卡 30
     * @return bool
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @author 李高鹏^life <453885726@qq.com>
     */
    public function pay( $order_code = '' , $pay_type = 0  , $goods_num = 1){
        $orderInfo = $this->where(  ['order_code' => $order_code] )->find();
        if( !$orderInfo ){
            return false;
        }
        //获取旧会员信息
        $memberModel = new old_member();
        $member = $memberModel->where( array( 'member_id' => $orderInfo['member_id']) )->find();
        if( !$member ){
            return false;
        }
        //嘉和卡
        if( $pay_type == 5 ){
            //卡消费
            $cxjApi = new CxjSdk();
            $cxjApi->setAction( 'cardConsume');
            $result = $cxjApi->getResult( ['order_code'=> $order_code ] );
            if( $result  && $result['code'] == 1 ){
                $this->paySuccess( $order_code );
                return true;
            } else {
                return false;
            }
        }
        //早餐月卡  共享早餐卡
        if( $pay_type == 25){
            $memberCard = new memberCard();
            $memberCard->updateCard( $orderInfo['member_id'] ,  1  , 1 , $orderInfo['order_id'] );
            $this->paySuccess( $order_code );
            return true;
        }
        //共享早餐卡
        if(  $pay_type == 30){
            $memberCard = new memberCard();
            $memberCard->updateCard( $orderInfo['member_id'] ,  2  , $goods_num , $orderInfo['order_id'] );
            $this->paySuccess( $order_code );
            return true;
        }
    }

    /**
     *微信支付
     * @param array $param
     * @param array $orderGoods  订单商品信息
     * @return bool
     */
    public function wxpay(   $param = array() , $orderGoods = array() ){

        if( !isset( $param['order_code'] ) ||  !isset( $param['total_price']) ||
            !isset( $param['openid']) || !isset( $param['store_id']) ||
            !isset( $param['store_name']) ||  !isset( $param['token'])
        ){
            $this->error = '缺少参数';
            return false;
        }

        $orderInfo = $this->where(  ['order_code' => $param['order_code'] ] )->field('order_id,member_id,coupon_id')->find();

        if(!$orderInfo){
            $this->error = '订单不存在';
            return false;
        }

        //判断价格是否0元 0元直接支付成功
        if( $param['total_price'] <= 0){
            $this->paySuccess( $param['order_code'] );
            return true;
        }
        $goods_tag = '';
        //判断是否可以使用单品
        $goodsList = config( 'site.dp_goodslist');

        $detail = [];
        foreach ( $orderGoods as $key => $item ){
            $detail[$key]['goods_id'] = $item['dishsno'];
            $detail[$key]['quantity'] = $item['amount'];
            $detail[$key]['goods_name'] = $item['goods_name'];
            $detail[$key]['price'] = $item['current_price'] *100;  //微信提交 分

            //判断是否有单品折扣商品
            if( in_array(  $item['dishsno'] , $goodsList) ){
                $goods_tag = $item['dishsno'] ;
            }
        }

        $url = config( 'old_url') . "/Home/pay/getWxParam";
        $data['key']       = md5('getWxParamabc' );

        if( !$orderInfo['coupon_id'] ){
            $data['detail']    = json_encode( $detail );
            $data['goods_tag'] = $goods_tag ;
        }

        $data = array_merge($data , $param);
        aw_log($data, 'tijiao.log');
        $res_json = postcurl( $url , $data );
        aw_log($res_json,'wx.log');
        aw_log($res_json, 'tijiao.log');
        $res_arr  = json_decode($res_json, true);

        if($res_arr['code'] == 0){
            return $res_arr['data'];
        } else {
            return false;
        }

        return true;
    }
    /**
     * 支付成功修改订单状态
     * @param sting $order_code
     * @param string trade_no 流水号
     */
    public function paySuccess( $order_code  = '' , $trade_no = '' ){
        $orderInfo = $this->where(  ['order_code' => $order_code] )->find();

        if( !$orderInfo ){
            return false;
        }

        //判断是否支付成功
        if(   $orderInfo['status_pay'] == 5    ){
            return true;
        }
        $data = array(
            'status_order' => 1,
            'status_pay'   => 5 ,
        );
        $this->where(  ['order_code' => $order_code] )->update( $data );




        //CXJ落单
        $cxjApi = new CxjSdk();

        $cxjApi->setAction( 'cxjCreateOrder');
        $cxjApi->setCurlAsyn( true );
        $result = $cxjApi->getResult( ['order_code'=> $order_code ] );
        if( $result  && $result['code'] == 1 ){

        } else {
            //落单失败 记录日志
            Log::write('CXJ落单失败 order_code:' . $order_code   . ' result: ' . json_encode( $result ) ,'notice');
        }

        //获取旧会员信息
        $memberModel = new old_member();
        $member = $memberModel->where( array( 'member_id' => $orderInfo['member_id']) )->find();
        if( !$member ){
            return false;
        }

        Log::write('CXJ_pay_success  result: ' . json_encode( $orderInfo ));
        //有金额 且支付方式微信时 才会增加
        if( $orderInfo['money_pay']  > 0  &&  $orderInfo['pay_type']  == 1){
            $cxjApi->setAction( 'setMemberScore');
            $cxjApi->setCurlAsyn( true );
            $score = $cxjApi->getResult( ['member_id'=> $orderInfo['member_id'] , 'order_id' =>$order_code  , 'type' => 1 , 'score' =>$orderInfo['money_pay'] ] );
            if( $score && $score['code'] == 1 ){

            } else {
                //落单失败 记录日志
                Log::write('CXJ下单增加积分失败 order_code:' . $order_code   . ' result: ' . json_encode( $score ) ,'notice');
//                return false;
            }
        }

        //判断小程序 发送消息推送
        if( $orderInfo['source'] == 1 ){
            try{
                //消息推送下单
                $url = 'http://' . $_SERVER['HTTP_HOST'] . '/api/order/orderSendMessage';
                $pushResult = postcurl( $url , ['order_code' => $order_code , 'type_send' => 2] , true);
                if( !$pushResult ){
                    //落单失败 记录日志
                    Log::write('微信消息推送失败:' . $order_code   . ' result: ' . json_encode( $pushResult ) ,'notice');
                }
            } catch (\Exception $e) {
                Log::write('微信消息推送失败catch:' . $order_code   . ' result: ' . json_encode( $e->getMessage() ) ,'notice');
            }
        }
        //餐行健 落单

        return true;
    }


    public function sendCommonMsg( $order_id = 0 ){

        if(!$order_id ){
            return true;
        }
        $cxjApi = new CxjSdk();
        $cxjApi->setAction( 'sendCommonMsg');
        $cxjApi->setCurlAsyn( true );
        $cxjApi->getResult( ['order_id'=> $order_id ] );
        return true;
    }


    /**
     * 增加消费记录
     * @param string $order_code  //订单编号
     */
    public function addOrderLog( $order_code = ''){
        $orderInfo = $this->where(  ['order_code' => $order_code] )->find();

        if( !$orderInfo ){
            return false;
        }

        //获取用户信息
        $memberModel = new old_member();
        $member = $memberModel->where( array( 'member_id' => $orderInfo['member_id'] , 'member_status' => 1 ))->field( 'member_id,open_id' )->find();

        if( !$member ){
            return false;
        }
        if( !$member['open_id']){
            return false;
        }
        //增加pay表
        $payModel = new Pay();
        $payModel->save([
           'status' => 1 ,
            'order_id' => $orderInfo['order_id'] ,
            'order_code' => $orderInfo['order_code'],
            'money'    => $orderInfo['money_pay'],
            'pay_type' => 30,
            'store_id' => $orderInfo['store_id'],
            'pay_user' => $member['open_id'],
            'table'    => $orderInfo['table_num'],
            'create_time' => date( 'Y-m-d H:i:s' , time() )
        ]);
        //增加paylog表
        $payLogModel = new PayLog();
        $payLogModel->save([
            'pay_status' => 30 ,
            'order_code' => $orderInfo['order_code'],
        ]);

        return true;
    }

    /**
     * @param int $pay_type 支付类型  1微信  5嘉和卡 25早餐月卡  30共享早餐卡
     * @param $member_id      用户id 旧平台
     * @param int $price      订单价格
     * @param int $goods_num  商品数量
     * @param int $store_id   门店id
     * @return bool
     * @author 李高鹏^life <453885726@qq.com>
     */
    public function checkPayType( $pay_type = 0 , $member_id  , $price = 0  , $goods_num = 0 , $store_id ){


        //支付方式 1微信  5嘉和卡 25早餐月卡  30共享早餐卡
        $payTypeArr = [ 1 ,5 , 25 , 30];
        if( !in_array($pay_type, $payTypeArr )){
            $this->error = '未知的支付方式';
            return false;
        }
        if( $pay_type == 5 ){
            return $this->checkJhCard( $member_id , $price);
        }

        if( $pay_type == 25 ){
            return $this->checkMonthCard( $member_id , 1  , $goods_num , $store_id);
        }

        if( $pay_type == 30 ){
            return $this->checkMonthCard( $member_id , 2  , $goods_num  , $store_id);
        }

        return true;

    }
    /**
     * 提交订单 - 验证嘉和卡余额是否满足
     * @param int $member_id 会员Id 旧平台
     * @param int $price 金额
     */
    public function checkJhCard( $member_id = 0 , $price = 0 ){

        //获取会员信息
        $memberModel = new old_member();
        $member = $memberModel->where( array( 'member_id' => $member_id ) )->field('member_id , union_id')->find();

        if( !$member ){
            $this->error = '用户不存在';
            return false;
        }

        $cxjApi = new CxjSdk();
        $cxjApi->setAction( 'getJhCard');
        $result = $cxjApi->getResult( ['union_id'=> $member['union_id']] );

        if( $result  && $result['code'] == 1 ){
            //判断用户余额是否满足
            if( $price > $result['data']['memberinfo'][0]['totalbalance']){
                $this->error = '余额不足';
                return false;
            }
        } else {
            $this->error = '下单失败';
            return false;
        }

        return true;
    }

    /**
     * 验证月卡
     * @param int $type  1早餐月卡 2共享月卡
     * @param int $goodsNum 商品数量
     * @param int $member_id  旧用户Id
     */
    public function checkMonthCard( $member_id , $type  , $goodsNum = 0  , $store_id){

        $store_server = new storeServer();
        //判断是否在早餐时间段
        $morning_status = $store_server->isMorning($store_id);
        if( !$morning_status ){
            $this->error = '当前不在早餐时间';
            return false;
        }
        $memberCardModel = new memberCard();
        $memberCardLogModel = new memberCardLog();

        //获取卡信息
        $condition['member_id'] = $member_id;
        $condition['status'] = memberCard::$status_on;
        $condition['type']   = $type;
        $cardData = $memberCardModel->where( $condition )->find();

        if( empty( $cardData ) ){
            $this->error = '未找到卡信息';
            return false;
        }
        if( $cardData['rest_times'] <= 0 ){
            $this->error = '月卡次数已用完';
            return false;
        }
        $nowTime = date('Y-m-d H:i:s');
        if($cardData['time_end'] < $nowTime ){
            $this->error = '月卡已过期，请重新购买';
            return false;
        }
        if( $type == 1  && $cardData['type'] ==  $type){
            //早餐月卡一日使用一次
            $cardLogData = $memberCardLogModel->where(['card_id'=>$cardData['code'],'create_time'=>['gt',date("Y-m-d 00:00:00")]])->count();
            if(!empty($cardLogData)){
                $this->error = '当前卡每天只能使用一次';
                return false;
            }
        }
        //共享卡剩余次数
        if( $type == 2  && $cardData['type'] == $type ){
            if($cardData['rest_times'] < $goodsNum ){
                $this->error = '共享早餐卡剩余次数不足';
                return false;
            }
        }
        return true;
    }

    /**
     * 验证优惠券是否满足使用条件
     * @param int 会员id 旧平台
     * @param int 优惠券id
     */
    public function checkCoupons( $memebr_id , $coupons_id ){

        $couponsModel = new Coupons();
        $coupons = $couponsModel->where( array( 'onwer' => $memebr_id  , 'coupon_id' => $coupons_id))->field( 'coupon_id , status_coupon , time_start , time_expired , is_lock')->find();
        if( !$coupons ){
            return false;
        }
        //判断状态
        if( $coupons['status_coupon'] != 2 ){
            return false;
        }
        //判断是否在可用时间内
        $that_time = date( 'Y-m-d H:i:s' , time() );
        if( $coupons['time_start'] >  $that_time  ||  $coupons['time_expired'] < $that_time){
            return false;
        }

        return true;
    }


    /**
     * 整理数据
     * @param array $item
     * @param array $goodsInfo
     * @return mixed
     * @author 李高鹏^life <453885726@qq.com>
     */
    public function setOrderItemParam( $item = array() , $goodsInfo = array() ) {

        $marketingType = isset($item['marketingType'])  ? $item['marketingType'] : 0 ;
        $isZeng  =  isset($item['isZeng']) ? $item['isZeng'] : 0;
        $isHuan  =  isset($item['isHuan']) ? $item['isHuan'] : 0;
        $isSet   =  isset($item['isSet']) ? $item['isSet'] : 0;
        //订单商品信息
        $orderGoods = [
            "amount"   => $item['num'],
            "goods_id" => $goodsInfo['dkid'],
            "goods_name" => $goodsInfo['name'],
            "old_price"  => $goodsInfo['current_price'],
            "goods_unit"    => $goodsInfo['unit'],
            "current_price" => $goodsInfo['member_price'],
            'create_time'   => date('Y-m-d H:i:s' , time() ),
            'marketing_type' =>$marketingType ,
            'goods_type' => ($isZeng || $isHuan ) ? $marketingType : 0,
            'marketing_id' => isset($item['marketingId']) ? $item['marketingId']: 0,
            'is_set' => $isSet,
            'store_goods_id' => $goodsInfo['store_goods_id'],
            'dishsno' => $item['dishsno']  //商品速记码
        ];

        return $orderGoods;

    }


}